package com.ruoyi.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.mapper.HotelMapper;
import com.ruoyi.mapper.HouseMapper;
import com.ruoyi.mapper.RPMapper;
import com.ruoyi.service.GroundService;
import com.ruoyi.service.HotelService;
import com.ruoyi.service.JurisdictionService;
import com.ruoyi.utils.ElongUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelServiceImpl implements HotelService {

    @Autowired
    HotelMapper hotelMapper;

    @Autowired
    GroundService groundService;

    @Autowired
    RPMapper rpMapper;

    @Autowired
    HouseMapper houseMapper;

    @Autowired
    JurisdictionService jurisdictionService;

    @Override
    public List<Map> getHotelList(Map map) {
        map.put("jurisdiction", jurisdictionService.getHotelDataPermissionsAndCompleteSQL());
        return hotelMapper.getHotelList(map);
    }

    @Override
    public Map getHotelByHotelId(String hotelId) {
        return hotelMapper.getHotelObjByHotelId(hotelId);
    }

    @Override
    public AjaxResult postAddHotel(JSONObject jsonObject) {

        // 判断该酒店是否添加
        String eHotelId = jsonObject.getString("eHotelId");

        if (hotelMapper.getHotelCountByeHotelId(eHotelId) > 0) {
            // 酒店已添加
            return AjaxResult.error("酒店已添加！");
        } else {
            if (jsonObject.get("hotelCityId") != null && jsonObject.getJSONArray("hotelCityId").size() == 2) {
                JSONArray jsonArray = jsonObject.getJSONArray("hotelCityId");
                jsonObject.put("sfid", jsonArray.getInteger(0));
                jsonObject.put("sjid", jsonArray.getInteger(1));
            }
            int i = hotelMapper.insertAddHotel(jsonObject);
            if (i > 0) {
                String hotelId = jsonObject.getString("hotelId");
                hotelMapper.insertHotelWeekEndDefault(hotelId);
                return AjaxResult.success();
            } else {
                return AjaxResult.error("添加失败,请联系管理员！");
            }
        }
    }

    @Override
    public int postEditHotel(JSONObject jsonObject) {
        System.out.println(jsonObject);
        if (jsonObject.get("hotelCityId") != null && jsonObject.getJSONArray("hotelCityId").size() == 2) {
            JSONArray jsonArray = jsonObject.getJSONArray("hotelCityId");
            jsonObject.put("sfid", jsonArray.getInteger(0));
            jsonObject.put("sjid", jsonArray.getInteger(1));
        }
        return hotelMapper.updateHotelByMap(jsonObject);
    }

    @Override
    public List<Map> getHotelListAll() {
        Map map = new HashMap();
        map.put("jurisdiction", jurisdictionService.getHotelDataPermissionsAndCompleteSQL());
        return hotelMapper.getHotelListAll(map);
    }

    @Override
    public JSONObject getMapping(String hotelId) {
        /*
        try {
            List<Map> hotelListAll = hotelMapper.getHotelListAll(new HashMap());
            for (Map map : hotelListAll) {
                String hotelId1 = map.get("hotelId").toString();
                JSONObject mapping = groundService.getMapping(hotelId1);
                String a = mapping.getString("body");
                JSONObject jsonObject = JSONObject.parseObject(a);
                JSONArray jsonArray = jsonObject.getJSONArray("mappingList");
                JSONArray jsonArray1 = jsonArray.getJSONObject(0).getJSONArray("roomTypeMappingList");
                for (int i = 0; i < jsonArray1.size(); i++) {
                    JSONObject jsonObject1 = jsonArray1.getJSONObject(i);
                    Map map1 = new HashMap();
                    map1.put("houseId",jsonObject1.getString("supplierRoomTypeID"));
                    map1.put("isOnline","1");
                    houseMapper.updateHouseByMap(map1);
                }
                Thread.sleep(1500);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
         */
        return groundService.getMapping(hotelId);
    }

    public static void setText(String text) {
        try {
            String filePath = "D:/1.txt"; // 文件路径
            String contentToAppend = text + "\n"; // 要追加的内容

            // 创建FileWriter实例，传入true表示追加内容
            FileWriter writer = new FileWriter(filePath, true);

            // 使用writer写入内容
            writer.write(contentToAppend);

            // 关闭writer
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public int postIsFreeCancelable(Map map) {
        String status = map.get("statu").toString();
        Map map1 = (Map) map.get("dataStr");
        String hotelId = map1.get("hotelId").toString();
        int opType;
        if ("true".equals(status)) {
            opType = 1;
        } else {
            opType = 0;
        }
        JSONObject jsonObject = groundService.processFreeCancelPolicy(hotelId, opType);
        if (jsonObject.getInteger("retcode") == 0) {
            Map map2 = new HashMap();
            map2.put("hotelId", hotelId);
            if ("true".equals(status)) {
                map2.put("isFreeCancelable", 1);
            } else {
                map2.put("isFreeCancelable", 0);
            }
            hotelMapper.updateHotelByMap(map2);
            return 1;
        }
        return 0;
    }

    @Override
    public int postUpdateRoomRatePlanPolicy(JSONObject jsonObject) {
        String hotelId = jsonObject.getString("hotelId");
        int isCancel = jsonObject.getInteger("isCancel");
        boolean canBeCanceled = false;
        if (isCancel == 1) {
            canBeCanceled = true;
        } else {
            canBeCanceled = false;
        }
        int beforeFreeCancel = jsonObject.getInteger("beforeFreeCancel");
        int chargedChargeCancel = 24 - jsonObject.getInteger("chargedChargeCancel");
        String cancelStartTime = DateUtils.getDate();
        String cancelEndTime = DateUtils.getFutureDateAsString(365);
        int contractProportion = jsonObject.getInteger("contractProportion");
        List<Map> rpList = rpMapper.getRpList(hotelId);

        int i = 0;
        for (Map map : rpList) {
            String rpId = map.get("rpId").toString();
            JSONObject resJonObj = groundService.updateRoomRatePlanPolicy(hotelId, rpId, cancelStartTime, canBeCanceled, 0, beforeFreeCancel, chargedChargeCancel, 2, cancelEndTime, contractProportion);
            if (resJonObj.getInteger("retcode") == 0) {
                i++;
            }
        }

        if (i > 0) {
            Map map = new HashMap();
            map.put("hotelId", hotelId);
            map.put("isCancel", isCancel);
            map.put("beforeFreeCancel", beforeFreeCancel);
            map.put("chargedChargeCancel", jsonObject.getInteger("chargedChargeCancel"));
            map.put("contractProportion", contractProportion);
            map.put("cancelStartTime", cancelStartTime);
            map.put("cancelEndTime", cancelEndTime);
            hotelMapper.updateHotelByMap(map);
            return 1;
        } else {
            return 0;
        }
    }

    @Override
    public JSONObject getHotelInfo(String eHotelId) {
        String hotelInfo = ElongUtils.getHotelInfo(eHotelId);
        JSONObject jsonObject = JSONObject.parseObject(hotelInfo);
        JSONObject jsonObject1 = jsonObject.getJSONObject("Result").getJSONObject("Detail");

        JSONObject jsonObject2 = new JSONObject();
        jsonObject2.put("HotelId", jsonObject1.getString("HotelId"));
        jsonObject2.put("HotelName", jsonObject1.getString("HotelName"));
        jsonObject2.put("Phone", jsonObject1.getString("Phone"));
        jsonObject2.put("Category", jsonObject1.getInteger("Category"));
        jsonObject2.put("Address", jsonObject1.getString("Address"));
        jsonObject2.put("GoogleLon", jsonObject1.getString("GoogleLon"));
        jsonObject2.put("GoogleLat", jsonObject1.getString("GoogleLat"));
        return jsonObject2;
    }

    @Override
    public int editLocalByOnline(String eHotelId, String hotelId) {
        JSONObject eHotelInfo = getHotelInfo(eHotelId);
        return hotelMapper.editLocalByOnline(eHotelInfo, hotelId);
    }

    @Override
    public List<Map> getSysUserInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Map map = new HashMap();
        // 如果是管理员,返回所有运营组用户
        if (loginUser.getUserId() != 1) {
            map.put("userId", loginUser.getUserId());
        }
        List<Map> sysUserInfo = hotelMapper.getSysUserInfo(map);
        return sysUserInfo;
    }

    @Override
    public List<Integer> getHotelWeekEndByHotelId(String hotelId) {
        return hotelMapper.getHotelWeekEndByHotelId(hotelId);
    }

    @Override
    public int postEditWeekEnd(JSONObject jsonObject) {
        String hotelId = jsonObject.getString("hotelId");
        // 先删除旧的
        hotelMapper.deleteWeekEndByHotelId(hotelId);
        int i1 = hotelMapper.insertHotelWeekEndManual(jsonObject);
        return i1;
    }

    @Override
    public void insertHotelWeekEndDefault() {
        List<Map> hotelListAll = hotelMapper.getHotelListAll(new HashMap());
        for (Map map : hotelListAll) {
            String hotelId = map.get("hotelId").toString();
            hotelMapper.insertHotelWeekEndDefault(hotelId);
        }
    }

    @Override
    public String getHotelIssueConfig(String hotelId) {
        return hotelMapper.getHotelIssueConfig(hotelId);
    }

    @Override
    public int postHotelIssueConfig(JSONObject jsonObject) {
        String configText = jsonObject.getString("value");
        String hotelId = jsonObject.getString("hotelId");
        hotelMapper.deleteIssueConfig(hotelId);
        int i = hotelMapper.insertIssueConfig(hotelId, configText);
        return i;
    }

    @Override
    public AjaxResult setCurrentHotel(String eSonHotelId) {
        Map map = new HashMap();
        map.put("eSonHotelId", eSonHotelId);
        List<Map> hotelList = hotelMapper.getHotelList(map);
        String sessionId = hotelMapper.getEBKSessionId();
        if (hotelList.size() > 0) {
            Map hotelInfo = hotelList.get(0);
            if (hotelInfo.get("userDun") != null) {
                String userDun = hotelInfo.get("userDun").toString();
                Map map1 = new HashMap();
                map1.put("User-Dun", userDun);
                map1.put("Cookie", "EbkSessionId=" + sessionId);

                JSONObject jsonObject = new JSONObject();
                jsonObject.put("hotelId", eSonHotelId);
                String resStr = HttpUtils.sendPostJsonHead("https://ebooking.elong.com/ebkcommon/currentHotel/setCurrentHotel", jsonObject.toString(), map1);
                JSONObject jsonObject1 = JSONObject.parseObject(resStr);
                System.out.println(jsonObject1);
                if (jsonObject1.getInteger("retcode") == 0) {
                    return AjaxResult.success();
                } else {
                    return AjaxResult.error();
                }
            } else {
                return AjaxResult.error("缺少关键数据");
            }
        } else {
            return AjaxResult.error();
        }
    }

    @Override
    public AjaxResult getPriceShowAllList() {
        String day = DateUtils.getDate1();
        String nextDay = DateUtils.getNextDay(day);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("check_in", day);
        jsonObject.put("check_out", nextDay);
        jsonObject.put("ticketPromotion", false);
        jsonObject.put("custom_level", 1);
        jsonObject.put("booking_channel", 3);
        jsonObject.put("showDays", 10);
        jsonObject.put("adultsNum", 2);
        String sessionId = hotelMapper.getEBKSessionId();

        Map map1 = new HashMap();
        map1.put("ebktoken", sessionId);
        map1.put("referer", "https://ebooking.elong.com");
        String resStr = HttpUtils.sendPostJsonHead("https://tcsyb.elong.com/syb/mini/priceShow/getPriceShowAllList", jsonObject.toString(), map1);
        JSONObject res = JSONObject.parseObject(resStr);
        if (res.getInteger("retcode") == 0) {
            // 改造一下数据
            JSONArray jsonArray = new JSONArray();
            JSONArray body = res.getJSONArray("body");
            // 循环房型
            for (int i = 0; i < body.size(); i++) {
                JSONObject house = body.getJSONObject(i);
                JSONArray rpList = house.getJSONArray("productList");
                for (int j = 0; j < rpList.size(); j++) {
                    JSONObject rp = rpList.getJSONObject(j);
                    String houseRpName = house.getString("sroomName") + "<" + rp.getString("productName") + ">";
                    boolean show = rp.getBoolean("show");
                    String detail = rp.getString("detail");
                    Map map = new HashMap();
                    map.put("houseRpName", houseRpName);
                    if (show) {
                        map.put("show", "已露出");
                    } else {
                        map.put("show", "未露出");
                    }

                    map.put("detail", detail);
                    jsonArray.add(map);
                }
            }
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("day", day);
            jsonObject1.put("priceShowAllList", jsonArray);
            return AjaxResult.success(jsonObject1);
        } else {
            return AjaxResult.error();
        }
    }
}
